/**
 * 
 */
package net.atomarrow.util.map;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Michael
 * 
 */
public class NumberMap<K, T extends Number> extends HashMap<K, Number> {
	private Map<K, Integer> count;

	public NumberMap() {
		super();
		count = new HashMap<K, Integer>();
	}

	/**
	 * 添加实体
	 * 
	 * @param key
	 * @param value
	 */

	public void addNumber(K key, T value) {
		Number num = get(key);
		if (num == null) {
			put(key, value);
			count.put(key, 1);
		} else {
			if (value instanceof Integer) {
				num = get(key).intValue() + value.intValue();
			} else if (value instanceof Double) {
				num = get(key).doubleValue() + value.doubleValue();
			} else if (value instanceof Float) {
				num = get(key).floatValue() + value.floatValue();
			} else if (value instanceof Long) {
				num = get(key).longValue() + value.longValue();
			} else if (value instanceof Short) {
				num = get(key).shortValue() + value.shortValue();
			} else if (value instanceof Byte) {
				num = get(key).byteValue() + value.byteValue();
			}
			put(key, num);
			count.put(key, count.get(key) + 1);
		}
	}

	/**
	 * 得到累计数值
	 */
	public T get(Object key) {
		return (T) super.get(key);
	}

	/**
	 * 计算平均分
	 * 
	 * @param key
	 * @return
	 */
	public double getAvg(Object key) {
		T value = (T) super.get(key);
		double num = -1;
		int n = count.get(key);
		if (value instanceof Integer) {
			num = get(key).intValue() / n;
		} else if (value instanceof Double) {
			num = get(key).doubleValue() / n;
		} else if (value instanceof Float) {
			num = get(key).floatValue() / n;
		} else if (value instanceof Long) {
			num = get(key).longValue() / n;
		} else if (value instanceof Short) {
			num = get(key).shortValue() / n;
		} else if (value instanceof Byte) {
			num = get(key).byteValue() / n;
		}

		return num;
	}

}
